//
//  ECMaterailManageFieldListViewController.m
//  ECERP.CRM
//
//  Created by huanggulong on 2018/11/22.
//  Copyright © 2018 Mac. All rights reserved.
//

#import "ECMaterailManageFieldListViewController.h"
#import "GLBaseHTTPTool.h"
#import "ECHTTPParam.h"

#import "ECMaterialUnit.h"
#import "ECMaterialBrand.h"
#import "ECMaterialRate.h"
#import "ECMaterialSave.h"
#import "ECMaterialAttendance.h"

@interface ECMaterailManageFieldListViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView * tableView;

@property (nonatomic,strong) NSMutableArray * dataArray;

@property (nonatomic,assign) NSInteger pageIndex;

@property (nonatomic,strong) UISearchBar * searchBar;

@end

@implementation ECMaterailManageFieldListViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setNavigation];
    [self setUI];
    [self.tableView.mj_header beginRefreshing];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.textColor = @"#333333".toColor;
    }
    if (self.fieldType == ECMaterailManageFieldTypeUnit1 || self.fieldType == ECMaterailManageFieldTypeUnit2) {
        ECMaterialUnit * unit = [self.dataArray objectAtIndex:indexPath.row];
        cell.textLabel.text = unit.UnitName?:@"--";
    }else if (self.fieldType == ECMaterailManageFieldTypeBrand) {
        ECMaterialBrand * brand = [self.dataArray objectAtIndex:indexPath.row];
        cell.textLabel.text = brand.BrandName?:@"--";
    }else if (self.fieldType == ECMaterailManageFieldTypeTaxRate) {
        ECMaterialRate * rate = [self.dataArray objectAtIndex:indexPath.row];
        cell.textLabel.text = rate.MaterialRate?:@"--";
    }else if (self.fieldType == ECMaterailManageFieldTypeStore) {
        ECMaterialSave * save = [self.dataArray objectAtIndex:indexPath.row];
        cell.textLabel.text = save.MaterialSaveName?:@"--";
    }else if (self.fieldType == ECMaterailManageFieldTypeSortZone){
        ECMaterialAttendance * attendance = [self.dataArray objectAtIndex:indexPath.row];
        cell.textLabel.text = attendance.AttendanceName?:@"--";
    }else{
        cell.textLabel.text = [NSString stringWithFormat:@"%ld - %ld",indexPath.section,indexPath.row];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 26)];
    label.backgroundColor = @"#f4f4f4".toColor;
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = @"#b3b3b3".toColor;
    label.text = [NSString stringWithFormat:@"    %@",[self fieldName]];
    return label;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 26;
}

#pragma mark - network
- (void)loadNewData{
    if (self.fieldType == ECMaterailManageFieldTypeUnit1 || self.fieldType == ECMaterailManageFieldTypeUnit2) {
        [self loadUnitData:0];
    }else if (self.fieldType == ECMaterailManageFieldTypeBrand){
        [self loadBrandData:0];
    }else if (self.fieldType == ECMaterailManageFieldTypeTaxRate){
        [self loadRateData:0];
    }else if (self.fieldType == ECMaterailManageFieldTypeStore){
        [self loadStoreData:0];
    }else if (self.fieldType == ECMaterailManageFieldTypeSortZone){
        [self loadAttendanceData:0];
    }
}

- (void)loadMoreData{
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
        return;
    }
    if (self.fieldType == ECMaterailManageFieldTypeUnit1 || self.fieldType == ECMaterailManageFieldTypeUnit2) {
        [self loadUnitData:1];
    }else if (self.fieldType == ECMaterailManageFieldTypeBrand){
        [self loadBrandData:1];
    }else if (self.fieldType == ECMaterailManageFieldTypeTaxRate){
        [self loadRateData:1];
    }else if (self.fieldType == ECMaterailManageFieldTypeStore){
        [self loadStoreData:1];
    }else if (self.fieldType == ECMaterailManageFieldTypeSortZone){
        [self loadAttendanceData:1];
    }
}

- (void)loadAttendanceData:(NSInteger)type{
    ECHTTPListParam * param = [ECHTTPListParam param];
    param.page = (type == 0)?1:self.pageIndex;
    param.limit = 20;
    [GLBaseHTTPTool getRequestURL:@"api/Material/GetAttendancePage" requestParam:param resultModelType:[ECMaterialAttendanceListResult class] success:^(ECMaterialAttendanceListResult * result) {
        if (result.code == 0) {
            if (result.data.count > 0) {
                if (type == 0) {
                    self.dataArray = result.data.mutableCopy;
                    self.pageIndex = 2;
                }else{
                    [self.dataArray addObjectsFromArray:result.data];
                    self.pageIndex += 1;
                }
                [self.tableView reloadData];
            }
        }else{
            [MBProgressHUD showText:result.msg?:@"拉取数据失败" toView:self.view];
        }
        [self endRefreshing];
    } failure:^(NSError *error) {
        [self endRefreshing];
        [MBProgressHUD showText:@"拉取数据失败" toView:self.view];
    }];
}

- (void)loadStoreData:(NSInteger)type{
    ECHTTPListParam * param = [ECHTTPListParam param];
    param.page = (type == 0)?1:self.pageIndex;
    param.limit = 20;
    [GLBaseHTTPTool getRequestURL:@"api/Material/GetMaterialSavePage" requestParam:param resultModelType:[ECMaterialSaveListResult class] success:^(ECMaterialSaveListResult * result) {
        if (result.code == 0) {
            if (result.data.count > 0) {
                if (type == 0) {
                    self.dataArray = result.data.mutableCopy;
                    self.pageIndex = 2;
                }else{
                    [self.dataArray addObjectsFromArray:result.data];
                    self.pageIndex += 1;
                }
                [self.tableView reloadData];
            }
        }else{
            [MBProgressHUD showText:result.msg?:@"拉取数据失败" toView:self.view];
        }
        [self endRefreshing];
    } failure:^(NSError *error) {
        [self endRefreshing];
        [MBProgressHUD showText:@"拉取数据失败" toView:self.view];
    }];
}

- (void)loadRateData:(NSInteger)type{
    ECHTTPListParam * param = [ECHTTPListParam param];
    param.page = (type == 0)?1:self.pageIndex;
    param.limit = 20;
    [GLBaseHTTPTool getRequestURL:@"api/Material/GetMaterialRatePage" requestParam:param resultModelType:[ECMaterialRateListResult class] success:^(ECMaterialRateListResult * result) {
        if (result.code == 0) {
            if (result.data.count > 0) {
                if (type == 0) {
                    self.dataArray = result.data.mutableCopy;
                    self.pageIndex = 2;
                }else{
                    [self.dataArray addObjectsFromArray:result.data];
                    self.pageIndex += 1;
                }
                [self.tableView reloadData];
            }
        }else{
            [MBProgressHUD showText:result.msg?:@"拉取数据失败" toView:self.view];
        }
        [self endRefreshing];
    } failure:^(NSError *error) {
        [self endRefreshing];
        [MBProgressHUD showText:@"拉取数据失败" toView:self.view];
    }];
}

- (void)loadBrandData:(NSInteger)type{
    ECHTTPListParam * param = [ECHTTPListParam param];
    param.page = (type == 0)?1:self.pageIndex;
    param.limit = 20;
    [GLBaseHTTPTool getRequestURL:@"api/Material/GetProductBrandPage" requestParam:param resultModelType:[ECMaterialBrandListResult class] success:^(ECMaterialBrandListResult * result) {
        if (result.code == 0) {
            if (result.data.count > 0) {
                if (type == 0) {
                    self.dataArray = result.data.mutableCopy;
                    self.pageIndex = 2;
                }else{
                    [self.dataArray addObjectsFromArray:result.data];
                    self.pageIndex += 1;
                }
                [self.tableView reloadData];
            }
        }else{
            [MBProgressHUD showText:result.msg?:@"拉取数据失败" toView:self.view];
        }
        [self endRefreshing];
    } failure:^(NSError *error) {
        [self endRefreshing];
        [MBProgressHUD showText:@"拉取数据失败" toView:self.view];
    }];
}

- (void)loadUnitData:(NSInteger)type{
    ECHTTPListParam * param = [ECHTTPListParam param];
    param.page = (type == 0)?1:self.pageIndex;
    param.limit = 20;
    [GLBaseHTTPTool getRequestURL:@"api/Material/GetMaterialUnitPage" requestParam:param resultModelType:[ECMaterialUnitListResult class] success:^(ECMaterialUnitListResult * result) {
        if (result.code == 0) {
            if (result.data.count > 0) {
                if (type == 0) {
                    self.dataArray = result.data.mutableCopy;
                    self.pageIndex = 2;
                }else{
                    [self.dataArray addObjectsFromArray:result.data];
                    self.pageIndex += 1;
                }
                [self.tableView reloadData];
            }
        }else{
            [MBProgressHUD showText:result.msg?:@"拉取数据失败" toView:self.view];
        }
        [self endRefreshing];
    } failure:^(NSError *error) {
        [self endRefreshing];
        [MBProgressHUD showText:@"拉取数据失败" toView:self.view];
    }];
}

- (void)endRefreshing{
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }else{
        [self.tableView.mj_footer endRefreshing];
    }
}

#pragma mark - private
- (NSString *)fieldName{
    NSString * title = @"----";
    switch (self.fieldType) {
        case ECMaterailManageFieldTypeUnit1:
        {
            title = @"商品单位";
            break;
        }
        case ECMaterailManageFieldTypeUnit2:{
            title = @"商品单位";
            break;
        }case ECMaterailManageFieldTypeBrand:{
            title = @"品牌";
            break;
        }case ECMaterailManageFieldTypeStore:{
            title = @"存储方式";
            break;
        }case ECMaterailManageFieldTypeTaxRate:{
            title = @"税率";
            break;
        }case ECMaterailManageFieldTypeSortZone:{
            title = @"分拣区域";
            break;
        }
        default:
            break;
    }
    return title;
}

- (void)setUI{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 54)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.offset(0);
        make.height.mas_equalTo(54);
    }];
    
    //搜索视图
    self.searchBar.layer.cornerRadius = 16;
    self.searchBar.clipsToBounds = YES;
    self.searchBar.layer.borderWidth = 1;
    self.searchBar.layer.borderColor = @"#cccccc".toColor.CGColor;
    [view addSubview:self.searchBar];
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(12*PX_RELATIVE375);
        make.top.offset(12);
        make.height.mas_equalTo(32);
        make.right.mas_offset(-5);
    }];
    //数据展示视图
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = @"#f4f4f4".toColor;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.and.bottom.offset(0);
        make.top.equalTo(view.mas_bottom);
    }];
}

#pragma mark - event
- (IBAction)rightClick:(id)sender{
    ECMaterailManageFieldAddViewController * vc = [[ECMaterailManageFieldAddViewController alloc] init];
    vc.fieldType = self.fieldType;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - network

#pragma mark - private
- (void)setNavigation{
    self.navigationItem.title = @"----";
    switch (self.fieldType) {
        case ECMaterailManageFieldTypeUnit1:
        {
            self.navigationItem.title = @"选择下单单位";
            break;
        }
        case ECMaterailManageFieldTypeUnit2:{
            self.navigationItem.title = @"选择结算单位";
            break;
        }case ECMaterailManageFieldTypeBrand:{
            self.navigationItem.title = @"选择品牌";
            break;
        }case ECMaterailManageFieldTypeStore:{
            self.navigationItem.title = @"选择存储方式";
            break;
        }case ECMaterailManageFieldTypeTaxRate:{
            self.navigationItem.title = @"选择税率";
            break;
        }case ECMaterailManageFieldTypeSortZone:{
            self.navigationItem.title = @"选择分拣区域";
            break;
        }
        default:
            break;
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"add_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(rightClick:)];
    
}

#pragma mark - getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.00000001)];
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.00000001)];
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.separatorColor = @"#f4f4f4".toColor;
        _tableView.sectionHeaderHeight = 27 * PX_RELATIVE375;
        _tableView.sectionFooterHeight = 0.00001 * PX_RELATIVE375;
        _tableView.rowHeight = 44;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [UISearchBar new];
        [_searchBar setImage:[UIImage imageNamed:@"search_member"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
        _searchBar.placeholder = @"搜索";
        [_searchBar setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]]];
        [_searchBar setPositionAdjustment:UIOffsetMake(-6, 0) forSearchBarIcon:UISearchBarIconSearch];
        for (UIView * v in _searchBar.subviews.firstObject.subviews) {
            if ([v isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                UITextField * tf = (UITextField*)v;
                tf.font = ECFONT(14);
            }
        }
    }
    return _searchBar;
}

@end
